package com.lingxu.base.system.manage.controller;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.DateUtil;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.common.util.encrypt.MD5Utils;
import com.lingxu.base.system.manage.entity.SortInfo;
import com.lingxu.base.system.manage.entity.SysDepart;
import com.lingxu.base.system.manage.entity.SysUser;
import com.lingxu.base.system.manage.entity.TSysUser;
import com.lingxu.base.system.manage.model.SysDepartUserTree;
import com.lingxu.base.system.manage.service.ISysDepartService;
import com.lingxu.base.system.manage.service.ISysUserService;
import com.lingxu.base.system.manage.vo.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 部门信息
 * @Author: LingXu
 * @Date:   2021-01-04
 * @Version: V1.0.1
 */
@Slf4j
@Api(tags="部门信息")
@RestController
@RequestMapping("/system/manage/sysDepart")
public class SysDepartController{
	@Resource
	private ISysDepartService sysDepartService;
	 @Resource
	 private ISysUserService sysUserService;

	/**
	 * 分页列表查询
	 *
	 * @param sysDepart
	 * @return
	 */
	@ApiOperation(value="部门信息-分页列表查询", notes="部门信息-分页列表查询")
	@PostMapping(value = "/list")
	public Result<SysDepart> queryPageList(@RequestBody SysDepart sysDepart) {
		Page<SysDepart> page = new Page<SysDepart>(sysDepart.getPageNo(), sysDepart.getPageSize());
		IPage<SysDepart> pageList = sysDepartService.queryPageList(page, sysDepart);
		return Result.ok(pageList);
	}

	 @ApiOperation(value="部门信息-获取部门树", notes="部门信息-获取部门树")
	 @RequestMapping(value = "/getSysDepartTree")
	 public Result getSysDepartTree(String pid) {
		 return sysDepartService.getSysDepartTree(pid);
	 }

	@ApiOperation(value="部门信息-获取部门树-预警", notes="部门信息-获取部门树-预警")
	@RequestMapping(value = "/findDepartTreeByPidAndEarlyWarn")
	public Result findDepartTreeByPidAndEarlyWarn(String pid) {
		return sysDepartService.findDepartTreeByPidAndEarlyWarn(pid);
	}

	@RequestMapping(value = "/findDepartTreeByLogin")
	public Result findDepartTreeByLogin() {
			return sysDepartService.findDepartTreeByLogin();
	}

	 @ApiOperation(value="部门信息-获取部门人员树", notes="部门信息-获取部门人员树")
	 @PostMapping(value = "/getSysDepartUserTree")
	 public Result<SysDepartUserTree> getSysDepartUserTree() {
//		 List<SysDepartTree> sysDepartTrees =
		 return sysDepartService.getSysDepartUserTree();
	 }


	private static String getNumber(String deptName){
		Map<String,String> map = new HashMap<>();
		map.put("一","1");
		map.put("二","2");
		map.put("三","3");
		map.put("四","4");
		map.put("五","5");
		map.put("六","6");
		map.put("七","7");
		map.put("八","8");
		map.put("九","9");
		map.put("十","1");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < deptName.length(); i++) {
			String dept = deptName.substring(i, i + 1);
			String s = map.get(dept);
			//20250310规避第十和第一 造成的已存在问题
			if(dept.equals("十") && map.get(deptName.substring(i+1, i+2)) == null){
				s = "10";
			}
			if(s != null){
				sb.append(s);
			}else {
				sb.append(dept);
			}
		}
		return sb.toString();
	}

	/**
	 * 添加
	 *
	 * @param sysDepart
	 * @return
	 */
	@ApiOperation(value="部门信息-添加", notes="部门信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysDepart sysDepart) {
		//校验部门唯一性
		int index = sysDepartService.findOne(sysDepart.getName());
		if(index > 0){
			return Result.error("当前已存在该部门名称：【" + sysDepart.getName() + "】");
		}
		//添加部门
		LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String deptId = UUID32Generator.generate();
		sysDepart.setId(deptId);
		sysDepart.setCreatetime(new Date());
		sysDepart.setCreateby(userNow.getId());
		sysDepartService.addOne(sysDepart);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param sysDepart
	 * @return
	 */
	@ApiOperation(value="部门信息-编辑", notes="部门信息-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody SysDepart sysDepart) {
		//TODO 根据sysDepart中的orgId，和orgCode生成出父子编码
		sysDepartService.updateById(sysDepart);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="部门信息-通过id删除", notes="部门信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id")@ApiParam(value = "部门id",required = true) String id,String ename) {
		List<SysDepart> sysDeparts = sysDepartService.queryDeptsByPid(id);
		if(sysDeparts!=null && sysDeparts.size()>0){
			return Result.error("该部门下还存在其他部门，请先删除子部门");
		}
		List<SysUser> list = sysUserService.queryListByDeptid(id);
		if(list!=null && list.size()>0){
			return Result.error("请先删除部门下人员");
		}
		sysDepartService.removeById(id);
		//删除用户信息
		sysUserService.deleteUserByName(ename);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="部门信息-批量删除", notes="部门信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids")@ApiParam(value = "部门id（多个用逗号','隔开）",required = true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		for(String id:list){
			List<SysDepart> sysDeparts = sysDepartService.queryDeptsByPid(id);
			if(sysDeparts!=null && sysDeparts.size()>0){
				return Result.error("该部门下还存在其他部门，请先删除子部门");
			}
			List<SysUser> sysUsers = sysUserService.queryListByDeptid(id);
			if(sysUsers!=null && sysUsers.size()>0){
				return Result.error("请先删除部门下人员");
			}
		}
		this.sysDepartService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="部门信息-通过id查询", notes="部门信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SysDepart> queryById(@RequestParam(name="id")@ApiParam(value = "部门id",required = true) String id) {
		SysDepart sysDepart = sysDepartService.getById(id);
		return Result.ok(sysDepart);
	}

	 @ApiOperation(value="部门信息-通过id查询下级部门", notes="部门信息-通过id查询下级部门")
	 @GetMapping(value = "/queryDeptsByPid")
	 public Result<?> queryDeptsByPid(@RequestParam(name="id")@ApiParam(value = "部门id",required = true) String id) {
		 List<SysDepart> sysDeparts = sysDepartService.queryDeptsByPid(id);
		 return Result.ok(sysDeparts);
	 }
	 /**
	  * 通过部门ids查询
	  * @param ids
	  * @return
	  */
	@ApiOperation(value="部门信息-通过ids查询", notes="部门信息-通过ids查询")
	@PostMapping(value = "/getByIds")
	public Result<SysDepart> queryByIds(@RequestParam(name="ids")@ApiParam(value = "部门id（多个用逗号','隔开）",required = true) String ids) {
		List<String> idList=Arrays.asList(ids.split(","));
		List<SysDepart> sysDeparts=sysDepartService.listByIds(idList);
		return Result.ok(sysDeparts);
	}

	 @ApiOperation(value = "改变部门排序", notes = "改变部门排序")
	 @PostMapping(value = "/changeDeptsSortNew")
	 public Result<?> changeDeptsSortNew(@RequestBody SortInfo sortInfo) {
		 if (StringUtils.isBlank(sortInfo.getId()) || sortInfo.getUp() == null) {
			 return Result.error("参数错误！");
		 }
		 boolean flag = sysDepartService.changeDeptsSortNew(sortInfo);

		 if(flag==true){
			 return Result.ok("操作成功");
		 }else{
			 return Result.error("操作失败！");
		 }

	 }




	 @RequestMapping(value = "/ddd")
	 public Result d(){

		 List<SysDepart> list = sysDepartService.d();

		 for(SysDepart sysDepart : list){
			 SysUser sysUser = new SysUser();
			 String userId = UUID32Generator.generate();
			 sysUser.setId(userId);
			 sysUser.setUsername(PinyinUtil.getFirstLetter(sysDepart.getName(),""));
			 String def = "MC5x.a4:";
			 sysUser.setPassword(MD5Utils.Md5Encrypt(def));
			 sysUser.setDeptid(sysDepart.getId());
			 sysUser.setDeptname(sysDepart.getName());
//			 sysUser.setCreateby(userNow.getId());
			 sysUser.setCreatetime(new Date());
			 sysUser.setName(sysDepart.getName());
			 sysUser.setRegion(sysDepart.getRegion());
			 sysUser.setRegionName(sysDepart.getRegionName());
			 sysUserService.save(sysUser);

			 //推送T_SYS_USER表
			 TSysUser tSysUser = new TSysUser();
			 tSysUser.setId(userId);
			 tSysUser.setUsername(sysUser.getName());
			 tSysUser.setAccount(sysUser.getUsername());
			 tSysUser.setFlag("03");
			 tSysUser.setStatus("01");
			 tSysUser.setDeptcode(sysUser.getDeptid());
			 tSysUser.setDeptname(sysUser.getDeptname());
			 tSysUser.setPassword(MD5Utils.Md5Encrypt(def));
			 tSysUser.setIdnumber(StringUtils.isEmpty(sysUser.getIdcard()) ? null : sysUser.getIdcard());
			 tSysUser.setCreatetime(DateUtil.getDateTime());
			 tSysUser.setRegion(sysUser.getRegion());
			 tSysUser.setRegionName(sysUser.getRegionName());
			 sysUserService.insertTSysUser(tSysUser);
		 }
		 return Result.ok();
	 }
}
